import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import aes from '@/utils/aes'
import { Message } from 'element-ui'

const user = {
  state: {
    id: getToken(),
    username: '',
    qq: '',
    tel: '',
    role: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.id = token
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_QQ: (state, qq) => {
      state.qq = qq
    },
    SET_ROLE: (state, role) => {
      state.role = role
    },
    SET_TEL: (state, tel) => {
      state.tel = tel
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const pwd = aes.encrypt(userInfo.password)
      console.log('加密后:' + pwd)
      return new Promise((resolve, reject) => {
        login(username, pwd).then(response => {
          if (response && response.id) {
            setToken(response.id)
            commit('SET_TOKEN', response.id)
            commit('SET_USERNAME', response.username)
            commit('SET_QQ', response.qq)
            commit('SET_ROLE', response.role)
            commit('SET_TEL', response.tel)
            resolve()
            console.log('登录成功')
          } else {
            Message({
              message: '用户名或密码错误',
              type: 'error',
              duration: 5 * 1000
            })
            reject('用户名或密码错误')
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.id).then(response => {
          if (response && response.id) {
            setToken(response.id)
            commit('SET_TOKEN', response.id)
            commit('SET_USERNAME', response.username)
            commit('SET_QQ', response.qq)
            commit('SET_ROLE', response.role)
            commit('SET_TEL', response.tel)
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_USERNAME', '')
        commit('SET_QQ', '')
        commit('SET_ROLE', '')
        commit('SET_TEL', '')
        removeToken()
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_USERNAME', '')
        commit('SET_QQ', '')
        commit('SET_ROLE', '')
        commit('SET_TEL', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
